package com.lushu.helpers {
import com.lushu.data.TilesetImage;
import com.lushu.info.ApplicationData;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;

import parts.renderer.ChargementBox;

public class TilesetReader extends EventDispatcher {
    private static var TILESET_LIST:Vector.<TilesetImage>

    private var toLoad_:int = 0;
    private var box_:ChargementBox;

    public function TilesetReader(box:ChargementBox) {
        box_ = box;
        var XML_URL:String = ApplicationData.BASE_LOCATION + "/" + ApplicationData.TILESET_DIRECTORY + "/discovery.php";
        var myXMLURL:URLRequest = new URLRequest(XML_URL);
        var myLoader:URLLoader = new URLLoader(myXMLURL);
        myLoader.addEventListener("complete", dirListed, false, 0, true);
    }

    private function dirListed(event:Event):void {
        box_.setSubLabel("Tileset : liste chargée");
        var tilesetString:String = event.target.data;
        var tilesetList:Array = tilesetString.split(":");
        var tilesetName:String;
        var currentTileset:TilesetImage;
        toLoad_ = tilesetList.length;
        TILESET_LIST = new Vector.<TilesetImage>();

        for (var i:int = 0; i < tilesetList.length; i++) {
            currentTileset = new TilesetImage(tilesetList[i], box_);
            currentTileset.addEventListener("tilesetLoaded", tilesetLoaded, false, 0, true);

            TILESET_LIST.push(currentTileset);
        }
    }

    private function tilesetLoaded(e:Event):void {
        toLoad_--;
        if (toLoad_ == 0) {
            dispatchEvent(new Event("allTilesetLoaded"));
        }
    }

    public static function getTileset():Vector.<TilesetImage> {
        return TILESET_LIST;
    }

    public static function getTilesetByName(name : String) : TilesetImage {
        for each(var tilesetImage : TilesetImage in TILESET_LIST)
        {
            if(tilesetImage.getName() == name)
                return tilesetImage;
        }
        return null;
    }
}
}